<template>
  <view class="chart-container">
    <canvas
      canvas-id="bloodSugarCanvas"
      :style="{ width: width + 'px', height: height + 'px' }"
    ></canvas>
  </view>
</template>

<script>
export default {
  name: "blood-sugar-chart",
  props: {
    width: { type: Number, default: 340 },
    height: { type: Number, default: 240 },
    data: {
      type: Array,
      default: () => [3.5, 4.2, 5.8, 6.5, 7.1, 4.9, 3.8],
    },
    xLabels: {
      type: Array,
      default: () => ["一", "二", "三", "四", "五", "六", "日"],
    },
  },
  mounted() {
    this.draw();
  },
  watch: {
    data: {
      handler() {
        this.$nextTick(() => this.draw());
      },
      deep: true,
    },
    xLabels: {
      handler() {
        this.$nextTick(() => this.draw());
      },
      deep: true,
    },
  },
  methods: {
    draw() {
      const ctx = uni.createCanvasContext("bloodSugarCanvas", this);
      const { width, height, data, xLabels } = this;

      const padding = 40;
      const contentW = width - padding * 2;
      const contentH = height - padding * 2;
      const hasSinglePoint = data.length === 1;
      const xStep = hasSinglePoint ? 0 : contentW / (data.length - 1);

      const max = Math.max(...data, 8);
      const min = Math.min(...data, 3);

      const dashLength = 5;
      const gapLength = 3;

      ctx.clearRect && ctx.clearRect(0, 0, width, height); // 清空画布

      // ===== 绘制横向辅助线（虚线） =====
      ctx.setFontSize(10);
      ctx.setFillStyle("#888");
      const yStep = (max - min) / 5;
      for (let i = 0; i <= 5; i++) {
        const val = (min + yStep * i).toFixed(1);
        const y = height - padding - (contentH / 5) * i;

        ctx.setStrokeStyle("#eee");
        ctx.setLineWidth(1);
        ctx.beginPath();
        for (let x = padding; x < width - padding; x += dashLength + gapLength) {
          ctx.moveTo(x, y);
          ctx.lineTo(x + dashLength, y);
        }
        ctx.stroke();

        ctx.fillText(val, 15, y + 3);
      }

      // ===== X轴 =====
      const xAxisY = height - padding;
      ctx.setStrokeStyle("#ccc");
      ctx.setLineWidth(1);
      ctx.beginPath();
      for (let x = padding; x < width - padding; x += dashLength + gapLength) {
        ctx.moveTo(x, xAxisY);
        ctx.lineTo(x + dashLength, xAxisY);
      }
      ctx.stroke();

      // ===== X轴标签 =====
      xLabels.forEach((label, i) => {
        const x = hasSinglePoint ? width / 2 : padding + i * xStep;
        ctx.setFillStyle("#666");
        ctx.setFontSize(10);
        ctx.setTextAlign("center");
        ctx.fillText(label, x, height - padding + 15);
      });

      // ===== 数据点 =====
      const points = data.map((val, i) => ({
        x: hasSinglePoint ? width / 2 : padding + i * xStep,
        y: height - padding - ((val - min) / (max - min)) * contentH,
        val,
      }));

      // ===== 平滑曲线 =====
      const smoothFactor = 0.25;
      ctx.setLineWidth(2);

      for (let i = 0; i < points.length - 1; i++) {
        const p0 = points[i - 1] || points[i];
        const p1 = points[i];
        const p2 = points[i + 1];
        const p3 = points[i + 2] || points[i + 1];

        const cp1x = p1.x + (p2.x - p0.x) * smoothFactor;
        const cp1y = p1.y + (p2.y - p0.y) * smoothFactor;
        const cp2x = p2.x - (p3.x - p1.x) * smoothFactor;
        const cp2y = p2.y - (p3.y - p1.y) * smoothFactor;

        let color;
        if (p2.val < 3.9) color = "#FDC24E";
        else if (p2.val <= 6.1) color = "#1EC157";
        else color = "#F56202";

        const grad = ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y);
        grad.addColorStop(0, color);
        grad.addColorStop(1, color);

        ctx.beginPath();
        ctx.moveTo(p1.x, p1.y);
        ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, p2.x, p2.y);
        ctx.setStrokeStyle(grad);
        ctx.stroke();
      }

      // ===== 绘制节点 =====
      points.forEach((p) => {
        let color;
        if (p.val < 3.9) color = "#FDC24E";
        else if (p.val <= 6.1) color = "#1EC157";
        else color = "#F56202";

        ctx.beginPath();
        ctx.arc(p.x, p.y, 4, 0, 2 * Math.PI);
        ctx.setFillStyle(color);
        ctx.fill();

        ctx.beginPath();
        ctx.arc(p.x, p.y, 1.8, 0, 2 * Math.PI);
        ctx.setFillStyle("#fff");
        ctx.fill();

        ctx.setFillStyle("#333");
        ctx.setFontSize(10);
        ctx.setTextAlign("center");
        ctx.fillText(p.val.toFixed(1), p.x, p.y - 10);
      });

      ctx.draw();
    },
  },
};
</script>

<style scoped>
canvas {
  display: block;
}
.chart-container {
  width: 100%;
  display: flex;
  padding-left: 10rpx;
  justify-content: center;
}
</style>
